/*
 * ProfileSettingDetailsView.java
 *
 * Created on 12 Kasım 2008 Çarşamba, 12:50
 */
package org.testis.gui.mvc.view.testdesign;

import org.testis.gui.mvc.view.*;
import org.testis.gui.mvc.controller.testdesign.ProfileSettingDetailsController;
import org.testis.gui.mvc.controller.TestDesignControllerList;
import org.testis.gui.mvc.utilities.AtofProfileKeyTableModel;
import java.awt.Frame;
import java.awt.Point;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author  nurhat
 */
public class ProfileSettingDetailsView extends javax.swing.JDialog implements
        AbstractViewPanel {

    private static final long serialVersionUID = 21082374L;
    private TableRowSorter<TableModel> sorter;

    /** Creates new form ProfileSettingDetailsView */
    public ProfileSettingDetailsView(java.awt.Frame parent,
            boolean modal) {
        super(parent,
                modal);
        initComponents();
        loadKeys();
    }

    public ProfileSettingDetailsView(Frame parent,
            boolean modal,
            AtofProfileKeyTableModel tableModel) {
        super(parent,
                modal);
        initComponents();
        sorter = new TableRowSorter<TableModel>(tableModel);
        profileDetailsTable.setRowSorter(sorter);
        profileDetailsTable.setModel(tableModel);
        loadKeys();

    }

    private TableModelListener addListener() {
        return new TableModelListener() {

            public void tableChanged(
                    TableModelEvent evt) {
                try {
                    if (evt.getType() ==
                            TableModelEvent.UPDATE) {
                        int column =
                                evt.getColumn();
                        if (column == 1) {
                            int row =
                                    profileDetailsTable.getSelectedRow();

                            String currentParameter =
                                    (String) profileDetailsTable.getValueAt(
                                    row,
                                    0);
                            String currentValue =
                                    (String) profileDetailsTable.getValueAt(
                                    row,
                                    1);
                            if (currentValue.equals(txtValue.getText())) {
                                return;
                            }
                            TestDesignControllerList.newInstance().
                                    getProfileSettingDetailsController().
                                    operationEditPair(currentParameter,
                                    currentValue);
                            filterTable();
                            int result =
                                    javax.swing.JOptionPane.showConfirmDialog(null,
                                    "Do you want to apply this change to other profiles?",
                                    "Confirmation",
                                    javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                                    javax.swing.JOptionPane.QUESTION_MESSAGE);
                            if (result == javax.swing.JOptionPane.YES_OPTION) {
                                TestDesignControllerList.newInstance().getProfileSettingsSelectionController().startLoader(currentParameter, currentValue, false);
                            }
                        }


                    }
                } catch (Exception ex) {
                }
            }
        };
    }

    private void loadKeys() {
        cmbProfileKeys.removeAll();
        HashMap hp = TestDesignControllerList.newInstance().
                getProfileKeysController().operationGetKeys();
        Iterator iter = hp.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            cmbProfileKeys.add(entry.getValue().toString());
        }
        cmbProfileKeys.repaint();

    }

    private void filterTable() {
        String text = txtFilter.getText();
        if (text.length() == 0) {
            sorter.setRowFilter(null);
        } else {
            sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
        }
    }

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                ProfileSettingDetailsController.SHOW_VIEW)) {
            TestDesignControllerList.newInstance().
                    getProfileSettingDetailsController().
                    operationLoadDetails();
            this.setVisible(true);
        } else if (evt.getPropertyName().equals(
                ProfileSettingDetailsController.SHOW_ERROR)) {
            String val = (String) evt.getNewValue();
            JOptionPane.showMessageDialog(
                    this,
                    val,
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        } else if (evt.getPropertyName().equals(
                ProfileSettingDetailsController.PARAMETER_MODEL_CHANGED)) {
            profileDetailsTable.setModel((AtofProfileKeyTableModel) evt.getNewValue());
            profileDetailsTable.repaint();
            sorter = new TableRowSorter<TableModel>((AtofProfileKeyTableModel) evt.getNewValue());
            profileDetailsTable.setRowSorter(sorter);
            profileDetailsTable.getModel().addTableModelListener(addListener());
        } else if (evt.getPropertyName().equals(
                ProfileSettingDetailsController.CURRENT_PROFILE_ID)) {
            Integer profileId = (Integer) evt.getNewValue();
            String lblName = TestDesignControllerList.newInstance().
                    getProfileSettingDetailsController().operationGetProfileName(
                    profileId);
            lblProfileName.setText(lblName);

            String selectedKeyName = cmbProfileKeys.getSelectedItem();

            TestDesignControllerList.newInstance().
                    getProfileSettingDetailsController().
                    operationChangeProfileDetailVariable(selectedKeyName);
        } else if (evt.getPropertyName().equals(
                ProfileSettingDetailsController.CURRENT_SELECTED_KEYNAME)) {
            cmbProfileKeys.select((String) evt.getNewValue());

        } else if (evt.getPropertyName().equals(
                ProfileSettingDetailsController.CURRENT_SELECTED_KEYVALUE)) {
            String val = (String) evt.getNewValue();
            txtValue.setText(val);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnl1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        lblProfileName = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtValue = new javax.swing.JTextField();
        btnAddKey = new javax.swing.JButton();
        cmbProfileKeys = new java.awt.Choice();
        jLabel4 = new javax.swing.JLabel();
        txtFilter = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        profileDetailsTable = new javax.swing.JTable();
        btnRemove = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Profile Details");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        pnl1.setBackground(new java.awt.Color(241, 240, 235));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Settings for profile:");

        lblProfileName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblProfileName.setText("profileName");

        jLabel2.setText("Key:");

        jLabel3.setText("Value:");

        btnAddKey.setText("Add");
        btnAddKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddKeyActionPerformed(evt);
            }
        });

        cmbProfileKeys.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbProfileKeysItemStateChanged(evt);
            }
        });

        jLabel4.setText("Filter:");

        txtFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtFilterActionPerformed(evt);
            }
        });

        profileDetailsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        profileDetailsTable.setUpdateSelectionOnSort(false);
        profileDetailsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                profileDetailsTableMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(profileDetailsTable);

        btnRemove.setText("Remove Selected");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnl1Layout = new javax.swing.GroupLayout(pnl1);
        pnl1.setLayout(pnl1Layout);
        pnl1Layout.setHorizontalGroup(
            pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(btnRemove)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 305, Short.MAX_VALUE)
                .addComponent(btnExit)
                .addGap(20, 20, 20))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(pnl1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnl1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtFilter, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE))
                    .addComponent(btnAddKey, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(pnl1Layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblProfileName))
                    .addGroup(pnl1Layout.createSequentialGroup()
                        .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbProfileKeys, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                            .addComponent(txtValue, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE))))
                .addGap(172, 172, 172))
        );
        pnl1Layout.setVerticalGroup(
            pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblProfileName)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(cmbProfileKeys, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAddKey)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnExit)
                    .addComponent(btnRemove))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
    this.dispose();
}//GEN-LAST:event_btnExitActionPerformed

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    WindowListener[] listeners = getWindowListeners();
    for (int i = 0; i < listeners.length; i++) {
        this.removeWindowListener(listeners[i]);
    }
    this.setVisible(false);
    this.setEnabled(false);
    TestDesignControllerList.newInstance().getProfileSettingDetailsController().
            operationCloseWindow();
    this.dispose();
}//GEN-LAST:event_formWindowClosed

private void btnAddKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddKeyActionPerformed
    String key = cmbProfileKeys.getSelectedItem();
    String value = txtValue.getText().trim();
    TestDesignControllerList.newInstance().getProfileSettingDetailsController().operationAddPair(key, value);
    filterTable();
    int result =
            javax.swing.JOptionPane.showConfirmDialog(null,
            "Do you want to apply this change to other profiles?",
            "Confirmation",
            javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
            javax.swing.JOptionPane.QUESTION_MESSAGE);
    if (result == javax.swing.JOptionPane.YES_OPTION) {
        TestDesignControllerList.newInstance().getProfileSettingsSelectionController().startLoader(key, value, false);
    }

}//GEN-LAST:event_btnAddKeyActionPerformed

private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
    int startingRow =
            profileDetailsTable.getSelectedRow();
    if (startingRow >= 0) {
        String currentParameter =
                (String) profileDetailsTable.getValueAt(
                startingRow,
                0);
        String currentValue =
                (String) profileDetailsTable.getValueAt(startingRow,
                1);
        int result =
                javax.swing.JOptionPane.showConfirmDialog(null,
                "Are you sure?",
                "Confirmation",
                javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                javax.swing.JOptionPane.QUESTION_MESSAGE);
        if (result == javax.swing.JOptionPane.YES_OPTION) {
            TestDesignControllerList.newInstance().
                    getProfileSettingDetailsController().operationRemovePair(
                    currentParameter);
            filterTable();
            result =
                    javax.swing.JOptionPane.showConfirmDialog(null,
                    "Do you want to apply this change to other profiles?",
                    "Confirmation",
                    javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                    javax.swing.JOptionPane.QUESTION_MESSAGE);
            if (result == javax.swing.JOptionPane.YES_OPTION) {
                TestDesignControllerList.newInstance().getProfileSettingsSelectionController().startLoader(currentParameter, currentValue, true);
            }
        }
    }


}//GEN-LAST:event_btnRemoveActionPerformed

private void profileDetailsTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_profileDetailsTableMousePressed
    Point start = evt.getPoint();

    profileDetailsTable.changeSelection(profileDetailsTable.rowAtPoint(start),
            0,
            false,
            false);
    int startingRow =
            profileDetailsTable.getSelectedRow();
    String currentParameter =
            (String) profileDetailsTable.getValueAt(
            startingRow,
            0);
    String currentValue =
            (String) profileDetailsTable.getValueAt(startingRow,
            1);
    TestDesignControllerList.newInstance().getProfileSettingDetailsController().
            operationChangeProfileDetailVariable(currentParameter,
            currentValue);
}//GEN-LAST:event_profileDetailsTableMousePressed

private void cmbProfileKeysItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbProfileKeysItemStateChanged
    String selectedKeyName = cmbProfileKeys.getSelectedItem();
    TestDesignControllerList.newInstance().getProfileSettingDetailsController().
            operationChangeProfileDetailVariable(selectedKeyName);
}//GEN-LAST:event_cmbProfileKeysItemStateChanged

private void txtFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFilterActionPerformed
    filterTable();
}//GEN-LAST:event_txtFilterActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddKey;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnRemove;
    private java.awt.Choice cmbProfileKeys;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblProfileName;
    private javax.swing.JPanel pnl1;
    private javax.swing.JTable profileDetailsTable;
    private javax.swing.JTextField txtFilter;
    private javax.swing.JTextField txtValue;
    // End of variables declaration//GEN-END:variables
}
